/**
 * 封装请求
 * @param {String} uri 请求路径
 * @param {Object} _params 请求参数
 * @param {Boolean} showToast 是否显示loading
 * @param config
 */
import { deepCopy } from "@/helper/utils";
import Taro from "@tarojs/taro";
import { SingleApi } from "@/constants/api";
import interceptors from "./interceptors";
import hosts from "@/constants/hosts";

/**
 * 响应请求拦截器
 */
Taro.addInterceptor(Taro.interceptors.timeoutInterceptor);
Taro.addInterceptor(Taro.interceptors.logInterceptor);
Taro.addInterceptor(interceptors.parseData);
/**
 * 封装请求头参数。
 * @param uri
 * @param {Object} _params 请求参数
 */
const setConfig = (uri: SingleApi, _params) => {
  const options: Taro.request.Option<any> = {
    url: `${uri.baseUrl}${uri.url}`,
  };
  const token = "token";
  options.method = uri.method;
  options.header = {
    Authorization: token, // Authorization1.3.0
  };
  console.log("_params", _params);
  options.data = { ..._params };
  return options;
};

/**
 * 基础请求封装
 * @param opts
 * @param showToast
 */
const baseRequest = async (opts: any, showToast: boolean) => {
  if (showToast) {
    Taro.showLoading({
      title: "正在加载...",
      mask: true,
    });
  }
  let res = {};
  console.log("opts", opts);
  try {
    res = await Taro.request(opts);
    Taro.hideLoading();
  } catch (e) {
    res = e;
    Taro.hideLoading();
    console.log("request fail : ", e);
  }
  return res;
};

const request = async (
  uri: any,
  _params = {} as any,
  showToast = true,
  config = {} as any
) => {
  const params = deepCopy(_params);

  Object.assign(config, setConfig(uri, params));
  // toastFn(showToast)();
  return baseRequest(config, showToast);
};

export default request;

export const uploadFileApi = (filePath) => {
  return new Promise((resolve, reject) => {
    Taro.uploadFile({
      url: `${hosts.baseUrl}/common/uploadFile`,
      filePath: filePath,
      name: "file",
      header: { "Content-Type": "multipart/form-data" },
      formData: {
        user: "test",
      },
      success(res) {
        const data = res.data;
        resolve(JSON.parse(data));
      },
      fail(error) {
        reject(error);
      },
    });
  });
};
